package com.example.mvvmkotlin.inter

import android.app.Application
import android.util.Log
import androidx.lifecycle.MutableLiveData
import com.blankj.utilcode.util.GsonUtils
import com.fangmu.basemodule.BaseViewModel
import okhttp3.*
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.io.IOException

/**
 * @ProjectName : MvvmKotlin
 * @Author : FangMu
 * @Time : 2023/12/12 14:36
 * @Description : 文件描述
 */
open class InterViewModel(application: Application) : BaseViewModel(application) {
    val weather : String = ""
    val local = MutableLiveData<String>()

    fun getInfo() {
        //网络请求 okHttp
        val url = "http://apps.iyuba.cn/iyuba/titleApi.jsp?type=iOS&format=json&appId=100&maxid=0&pages=1&pageNum=10&parentID=0"
        val client = OkHttpClient()
        val request = Request.Builder().url(url).build()
        val call = client.newCall(request)
//        call.execute()//同步请求

        //GET 异步请求
        call.enqueue(object : Callback {
            override fun onFailure(call: Call, e: IOException) {
                //请求失败
                local.postValue("请求失败${e.toString()}")
                Log.e("TAG", "onFailure: ${e.toString()}")
            }

            override fun onResponse(call: Call, response: Response) {
                //请求成功
                if (response.isSuccessful) {
//                    response.body
                    val a = GsonUtils.toJson(request.body.toString())

                    local.postValue("请求成功: ${a.toString()}")

                }
            }

        })
    }
    fun retrofitGetAsync() {
        //
        val baseUrl = "https://www.wanandroid.com"
        val retrofit = Retrofit.Builder()
            .baseUrl(baseUrl)
            .addConverterFactory(GsonConverterFactory.create())
            .build()
        val server = retrofit.create(InterApiServer::class.java)
        server.getImagePath().enqueue(object : retrofit2.Callback<BaseMsg>{
            override fun onResponse(
                call: retrofit2.Call<BaseMsg>,
                response: retrofit2.Response<BaseMsg>
            ) {
                val baseMsg = response.body()
                if (baseMsg != null) {
                    val dataList = baseMsg.data
                    local.postValue("请求成功: ${dataList[2].title}")
                }
            }
            override fun onFailure(call: retrofit2.Call<BaseMsg>, t: Throwable) {
                local.postValue("请求失败: ${t.message}")
            }
        })
    }
}